from typing import List, Optional
import requests
import math
from pyPodcastParser.Podcast import Podcast
from dataclasses import dataclass

from authors import Authors


@dataclass
class Post:
    id: int
    user_id: int
    title: str
    body: str
    audio_url: Optional[str] = None



class Blog:
    def __init__(self, per_page: int = 10) -> None:
        self.posts = self.__get_posts()
        self.per_page = per_page
        self.authors = Authors()
        self.parse_posts()

    def __get_posts(self) -> List[Post]:
        return []

    def get_all(self) -> List[Post]:
        return self.posts

    def get_by_page(self, posts: list[Post] = None, page: int = 1) -> List[Post]:
        if posts is None: posts = self.posts
        start_post_index = (page - 1) * self.per_page
        end_post_index = page * self.per_page
        return posts[start_post_index:end_post_index]

    def get_pages_count(self, posts: list[Post] = None) -> List[int]:
        if posts is None: posts = self.posts
        return [i+1 for i in range(math.ceil(len(posts) / self.per_page))]

    def get_posts_by_user_id(self, user_id: int) -> List[Post]:
        posts = []
        for p in self.posts:
            if p.user_id == user_id:
                posts.append(p)
        return posts

    def get_post_by_id(self, post_id: int) -> Post | None:
        for p in self.posts:
            if p.id == post_id:
                return p
        return None

    def parse_posts(self):
        for l in ['https://soundcloud.com/bvgm', 'https://www.prahladanandaswami.com/index.php/feed/podcast/', 'https://bvks.ru/podcast/itunes/']:
            
            if l.split('/')[2] == 'soundcloud.com':
                l = get_feed_url_from_soundcloud(l) 
            r = requests.get(l)
            podcast = Podcast(r.content)

            author = self.authors.get_user_by_name(podcast.itunes_author_name)
            if author.id == 666:
                author.id = self.authors.add_author(
                    name=podcast.itunes_author_name,
                    info=podcast.description,
                    url=l
                )

            posts = []
            counter = len(self.posts)

            for a in podcast.items[::-1]:
                counter += 1
                posts.append(
                    Post(
                        id=counter,
                        user_id=author.id,
                        title=a.title,
                        body=a.description,
                        audio_url=a.enclosure_url
                    )
                )
            self.posts = posts[::-1] + self.posts


    def add_post(self, post: Post) -> Post:
        self.posts.insert(0, post)
        print(self.posts[0])
        return post

def get_feed_url_from_soundcloud(url: str) -> str:

    from bs4 import BeautifulSoup
    html = requests.get(url)
    soup = BeautifulSoup(html.content, 'html.parser')
    data = soup.find("meta", property="al:android:url")
    url = data['content']
    user_id = url.split(':')[-1]
    return f'http://feeds.soundcloud.com/users/soundcloud:users:{user_id}/sounds.rss'



def get_fake_posts_data() -> list[Post]:
    r = requests.get('https://jsonplaceholder.typicode.com/posts')
    posts = r.json()
    posts.reverse()
    return [Post(
        id=p['id'],
        user_id=p['userId'],
        body=p['body'],
        title=p['title'].title()) for p in posts]
